<template>
  <div>
    <div class="search">
      <input v-model="keyword" type="text" placeholder="输入城市名/拼音" class="search-input">
    </div>
    <div v-show="keyword" class="search-content" ref="searchContent">
      <ul>
        <li
          v-for="item of list"
          :key="item.id"
          class="item border-bottom"
          @click="handleClickCityButton(item.name)"
        >
          {{item.name}}
        </li>
        <li v-show="hasNoData" class="item border-bottom">
          没有匹配的数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: '',
      list: [], // 存放匹配keyword的数据
      timer: null
    }
  },
  computed: {
    hasNoData () {
      return this.list.length <= 0
    }
  },
  methods: {
    handleClickCityButton (name) {
      this.changeCity(name)
      this.$router.push('/')
    },
    ...mapMutations({
      changeCity: 'CHANGE_CITY'
    })
  },
  watch: {
    keyword () {
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.timer = setTimeout(() => {
        let result = []
        if (this.keyword === '') {
          this.list = []
          return
        }
        for (let item in this.cities) {
          for (let innerItem of this.cities[item]) {
            if (innerItem.name.indexOf(this.keyword) > -1 || innerItem.spell.indexOf(this.keyword) > -1) {
              result.push(innerItem)
            }
          }
        }
        this.list = result
      }, 100)
    }
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.searchContent)
  }
}
</script>

<style lang="stylus" scoped>
  @import '~styles/variable.styl'
  .search
    height .72rem
    padding 0 .1rem
    background-color $themeColor
    .search-input
      margin-top .1rem
      padding 0 .1rem
      box-sizing border-box
      height .52rem
      width 100%
      border-radius .1rem
      text-align center
      color #333
      background-color #fff
  .search-content
    overflow hidden
    position absolute
    top 1.58rem
    bottom 0
    right 0
    left 0
    z-index 1
    background-color #eee
    .item
      line-height .70rem
      color #aaa
      padding-left .2rem
      background-color #fff
</style>
